package cn.yqn.service.impl;


import cn.yqn.domain.MovieTicket;
import cn.yqn.dto.UserMovieDto;
import cn.yqn.mapper.MovieTicketMapper;
import cn.yqn.result.JsonResult;
import cn.yqn.service.IMovieTicketService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author director
 * @since 2022-09-01
 */
@Service
public class MovieTicketServiceImpl extends ServiceImpl<MovieTicketMapper, MovieTicket> implements IMovieTicketService {

    @Autowired
    private MovieTicketMapper movieTicketMapper;

    // 购买
    @Override
    public JsonResult buy(Long userId, Long movieId) {
        // 1.查询库存，如果不足提示用户
        MovieTicket movieTicket = selectById(movieId);
        if (movieTicket.getStock() == 0){
            return JsonResult.error("库存不足，请联系管理员", "10001");
        }
        // 查询中间表
        UserMovieDto userMovieDto = movieTicketMapper.selectUserMovieByUserIdAndMovieId(userId, movieId);
        if (userMovieDto == null){
            // 如果中间表数据为空，说明用户没有买过，那么就新增
            UserMovieDto userMovieDto1 = new UserMovieDto(userId, movieId, 1);
            movieTicketMapper.insertUserMovie(userMovieDto1);
        }else {
            // 如果有说明用户买过，那么就修改
            userMovieDto.setCount(userMovieDto.getCount() + 1);
            movieTicketMapper.updateUserMovie(userMovieDto);
        }
        // 扣减库存
        movieTicket.setStock(movieTicket.getStock() - 1);
        updateById(movieTicket);
        return JsonResult.success(movieTicket.getPrice());
    }

    // 观看
    @Override
    public JsonResult watch(Long userId, Long movieId) {
        // 把用户要观看的电影票查询出来
        MovieTicket movieTicket = selectById(movieId);
        // 要观看的电影结束时间要大于当前时间
        if (movieTicket.getEndTime().getTime() < new Date().getTime()){
            return JsonResult.error("电影已结束，请观看其他电影！", "10002");
        }

        UserMovieDto userMovieDto = movieTicketMapper.selectUserMovieByUserIdAndMovieId(userId, movieId);
        if (userMovieDto == null){
            return JsonResult.error("请先购买电影票", "10003");
        }else {
            if (userMovieDto.getCount() < 1){
                return JsonResult.error("请先购买电影票", "10003");
            }
        }
        // 如果有说明用户买过，那么就修改
        userMovieDto.setCount(userMovieDto.getCount() - 1);
        movieTicketMapper.updateUserMovie(userMovieDto);

        return JsonResult.success("祝您观影愉快！", "200");
    }
}
